<template>
  <div class="paper_container">
    <div class="paper_content">
      <div class="paper-tool-header">
        <div class="cover-map">
          <!-- <div class="logo"><img src="/src/assets/knowledge-element/logo1.png" alt="logo"  /></div>
          <div class="title"><img src="/src/assets/knowledge-element/logo2.png" alt="title"  /></div> -->
        </div>
        <h1><input type="text" v-model="title" placeholder="请输入知识元标题"  @change="titleChange" /></h1>
      </div>
      <div class="paper_main">
        <div class="question_type">
          <!--     github issue  https://github.com/SortableJS/vue.draggable.next/issues/140     -->
          <draggable v-model="paperInfo.content" animation="250" item-key="id" @end="dragEnd" >
            <template #item="{ element, index }">
              <div class="question-title" >
                <div v-if="element.type === 1">
                  <div class="head-title" >
                    <el-popover placement="top" :width="300" trigger="click" popper-class="knowledge-popper">
                      <template #reference>
                        <div>
                          <img class="title-img" v-if="!choiceImg.map(i => i.cssType).includes(element.cssType)" src="/src/assets/knowledge-element/diqiu.png" alt="" height="40">
                          <template v-for="(imgItem, imgIdx) in choiceImg" :key="imgIdx" v-else>
                            <div class="title-img"><img :src="`${baseApi}${imgItem.filePath}`" alt="" height="40" v-if="element.cssType === imgItem.cssType"></div>
                          </template>
                        </div>
                      </template>
                      <div class="chioce-img" v-for="(imgItem, imgIdx) in choiceImg" :key="imgIdx" @click="changeImg(index, imgItem)"><img :src="`${baseApi}${imgItem.filePath}`" alt="" height="40"></div>
                    </el-popover>
                    <div class="title-editor">
                      <cus-editable-item  v-if="element.cssTitle" v-model="element.cssTitle" :autosize='1' @blur="editorBlur(element, index)"/>
                      <cus-editable-item v-else v-model="element.title" :autosize='1' @blur="editorBlur(element, index)"/>
                    </div>
                  </div>
                  <div class="footer">
                    <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle" >
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element,index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element,index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element,index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element,index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
                <div v-else-if="element.type === 2">
                  <cus-editable-item v-model="element.content" :autosize='1' @blur="editorBlur(element, index)"/>
                  <div class="footer">
                     <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle" >
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element,index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element,index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element,index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element,index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
                <div v-else-if="element.type === 3">
                  <div class="knowledgeTitle">知识点{{ element.index }}<cus-editable-item v-model="element.content"  :autosize='1' @blur="editorBlur(element, index)"/></div>
                  <div class="footer">
                    <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle" >
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element,index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element,index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element,index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element,index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
                <div v-else-if="element.type === 4" class="qustion-style">
                  <div class="title" ><div v-html="'<span style=\'color: #72b22a\'>例'+ element.index + '：</span>' + element.question.title"></div></div>
                  <div class="content" v-question="element.question"></div>
                  <div class="footer">
                    <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle">
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element, index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element, index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element, index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element, index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <div @click="changeQuestionType(element, index)"><span>改为变式</span></div>
                    <div @click="editQuestion(element, index)">
                      <span>编辑</span>
                    </div>
                    <div @click="addChangeQues(element, index)" v-if="!element.isChange">
                      <span>添加变式</span>
                    </div>
                    <div @click="questExchange(index, element.question.id)">
                      <i class="iconfont iconhuanti" />
                      <span>换题</span>
                    </div>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
                <div v-else-if="element.type === 8"  class="qustion-style">
                  <div class="title"><div v-html="'<span style=\'color: #72b22a\'>变式'+ `${element.index}-${element.title}`+ '：</span>' + element.question.title"></div></div>
                  <div class="content" v-question="element.question"></div>
                  <div class="footer">
                    <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle">
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element,index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element,index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element,index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element,index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <div @click="changeQuestion(element, index)"><span>改为例题</span></div>
                    <div @click="editQuestion(element, index)">
                      <span>编辑</span>
                    </div>
                    <div @click="questExchange(index, element.question.id)">
                      <i class="iconfont iconhuanti" />
                      <span>换题</span>
                    </div>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
                <div v-else-if="element.type === 9" class="qustion-style">
                  <div class="title" ><div v-html="'<span style=\'color: #72b22a\'>练习'+ element.index + '：</span>' + element.question.title"></div></div>
                  <div class="content" v-question="element.question"></div>
                  <div class="footer">
                    <el-dropdown trigger="click" placement="left" :offset='25' :show-arrow='false' @command="handle">
                      <span class="el-dropdown-link"><i class="el-icon-plus"/></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command='{ v, element, index }' v-for="v in addQuestion" :key="v">
                            添加{{ v }}
                            <div class="ques-btns" style="padding-buttom: 6px">
                              <el-button v-if="v === '例题'" size="mini" @click="quesAdd(element, index)">例题</el-button>
                              <!-- <el-button v-if="v === '例题'" size="mini" @click="xkwQuesAdd(element, index)">学科网例题</el-button> -->
                              <el-button v-if="v === '练习题'" size="mini" @click="practiceAdd(element, index)">练习题</el-button>
                              <!-- <el-button v-if="v === '练习题'" size="mini" @click="xkwPracticeAdd(element, index)">学科网练习题</el-button> -->
                            </div>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <div @click="editQuestion(element, index)">
                      <span>编辑</span>
                    </div>
                    <div @click="questExchange(index, element.question.id)">
                      <i class="iconfont iconhuanti" />
                      <span>换题</span>
                    </div>
                    <i class="iconfont iconshanchu" :class="{ 'is__disabled': paperInfo.content.length === 1 }" @click="deleteQuestType(element)" />
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, Ref, computed, onUnmounted } from 'vue';
import draggable from 'vuedraggable';
import store from './store';
import QuestionDirective from './../../utils/question.directive';
import ExchangeComponent from './components/exchange.vue';
import $, { emitter, clone, element } from '$';
import AddTitle from './components/add-title.vue';
import AddPaper from './components/add-paper.vue';
import AddKnowledge from './components/add-knowledge.vue'
import updateComponent from '@/views/question/components/update.vue'
import { useStore } from "vuex";


import { ElMessage } from 'element-plus';

export default {
  components: { draggable },
  directives: {
    question: QuestionDirective
  },
  props: {
    knowledgeData: {
      type: Object,
      default: () => ({})
    },
    subjectId: String
  },
  setup(props) {
    const rootStore = useStore()
    let title = computed({
      get: () => store.getters.title,
      set: (val) => store.commit('set_paper_title', val)
    });
    let paperInfo: Ref<any> = computed(() => store.state.paperInfo);
    let addKnowledge = ref(["标题","知识点", "段落", "例题", "练习题"])
    let addQuestion = ref(["标题","知识点", "段落", "例题", "练习题"])
    let baseApi = import.meta.env.VITE_APP_BASE_URL
    let subjectId = ''
    if (props.subjectId) {
      subjectId = props.subjectId
    } else {
      emitter.emit('effect', (subject) => subjectId = subject)
    }
    let choiceImg = ref([])
    const getImg = () => {
      $.http.post('/admin/icon/queryIcon', { subject: subjectId}).then((res: any) => {
        if (res.result) {
          choiceImg.value = res.json
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
    getImg()
    let moduleId: Ref<any> = computed(() => store.state.moduleId)

    const handle = (data) => {
      if(data.v ==='标题') {
        $.modal.create({
          title: '添加标题',
          zIndex: 2011,
          component: AddTitle,
          props: { data: data.element, addType: data.v, idx: data.index }
        }).then(res => {;
          let currentList = $.clone(paperInfo.value.content);
          currentList.splice(data.index + 1, 0, res)
          emitter.emit('pid-change', currentList)
          store.commit('set_paper_refresh', currentList)
        });
      } else if (data.v ==='段落') {
        let res = { content: '', type: 2, moduleId: data.element.moduleId}
        paperInfo.value.content.splice(data.index + 1, 0, res)
        emitter.emit('pid-change', paperInfo.value.content)
        store.commit('set_paper_refresh', paperInfo.value.content);
      } else if (data.v ==='知识点') {
        $.modal.create({
          title: '添加知识点',
          zIndex: 2011,
          component: AddKnowledge,
          props: { data: data.element }
        }).then(res => {
          let currentList = $.clone(paperInfo.value.content);
          res.type = 3
          res.cssType = 2
          res.moduleId = data.element.moduleId
          currentList.splice(data.index + 1, 0, res)
          emitter.emit('change-data', currentList)
          store.commit('set_paper_refresh', currentList);
        })
      }
    }
    /*添加例题*/
    const quesAdd = (element, index) => {
      $.drawer.create({
        title: '添加例题',
        closable: false,
        width: 'calc(100% - 200px)',
        component: AddPaper,
        props: { questionList: paperInfo.value.content, questionType: 4 }
      }).then(res => {
        let newQuestList = $.clone(res);
        let currentQuestList = $.clone(paperInfo.value.content);
        let pid = element.type === 4 ? null : element.id
        newQuestList.reverse().map((quest) => {
          currentQuestList.splice(index + 1, 0, { question: quest, score: 0, content: quest.id, moduleId: element.moduleId, type: 4, pid: pid })
        })
        emitter.emit('change-data', currentQuestList)
        store.commit('set_paper_refresh', currentQuestList)
      });
    }
    let xkwData: any = { element: null, index: ''}
    const xkwQuesAdd = (element: any, index) => openXKW(element, index, 4)
    /*添加练习题*/
    const practiceAdd = (element, index) => {
      $.drawer.create({
        title: '添加练习题',
        closable: false,
        width: 'calc(100% - 200px)',
        component: AddPaper,
        props: { questionList: paperInfo.value.content, questionType: 9 }
      }).then(res => {
        let newQuestList = $.clone(res);
        let currentQuestList = $.clone(paperInfo.value.content);
        let pid = element.type === 4 ? null : element.id
        newQuestList.reverse().map((quest) => {
          currentQuestList.splice(index + 1, 0, { question: quest, score: 0, content: quest.id, moduleId: element.moduleId, type: 9, pid: pid })
        })
        emitter.emit('change-data', currentQuestList)
        store.commit('set_paper_refresh', currentQuestList)
      });
    }
    const xkwPracticeAdd = (element, index) => openXKW(element, index, 9)
    const openXKW = (element, index, type) => {
      window.open(`${import.meta.env.VITE_APP_BASE_URL}/xkw/authentication?requestId=${encodeURIComponent(element.moduleId + '@knowledge@' + window.location.host )}&userId=${rootStore.getters.userInfo.user.id}`)
      xkwData = {element, index, type}
    }
    /*学科网页面关闭，刷新数据*/
    const __postMessageFn = event => {
      if (event.data.type === 'xkw_save') {
        $.http.post('admin/bizQuestionLog/queryQuestionByRelationId', {relationId: xkwData.element.moduleId}).then((res: any) => {
          if (res.result) {
            let currentQuestList = $.clone(paperInfo.value.content);
            let pid = xkwData.element.type === 4 ? null : xkwData.element.id
            res.json.reverse().map((quest) => {
              currentQuestList.splice(xkwData.index + 1, 0, { question: quest, score: 0, content: quest.id, moduleId: xkwData.element.moduleId, type: xkwData.type, pid: pid })
            })
            emitter.emit('change-data', currentQuestList)
            store.commit('set_paper_refresh', currentQuestList)
          } else {
            ElMessage.warning(res.msg)
          }
        })
      }
    };
    window.addEventListener('message', __postMessageFn);
    onUnmounted(() => window.removeEventListener('message', __postMessageFn));

    const addChangeQues = (data, index) => {
      $.drawer.create({
        title: '添加变式题',
        closable: false,
        width: 'calc(100% - 200px)',
        component: AddPaper,
        props: { questionList: paperInfo.value.content, questionType: 8 }
      }).then(res => {
        let newQuestList = $.clone(res);
        let currentQuestList = $.clone(paperInfo.value.content);
        newQuestList.map((quest) => {
        currentQuestList.splice(index + 1, 0,
         { question: quest, score: 0, content: quest.id, moduleId: data.moduleId, type: 8, pid: data.id })
        })
        emitter.emit('change-data', currentQuestList)
        store.commit('set_paper_refresh', currentQuestList);
      })
    }
    const deleteQuestType = (element) => {
      let data
      if(element.type === 4 && !element.isChange) {
        data = paperInfo.value.content.filter((p) => !(p.type === 4 && (p.id === element.id || p.pid === element.id)));
      }else {
        data = paperInfo.value.content.filter((p) => p.id !== element.id)
      }
      emitter.emit('change-data', data)
      emitter.emit('sort-change', data)
      store.commit('set_paper_content', data);
    }
    const dragEnd = (e) => {
      let currentQuestList = $.clone(paperInfo.value.content)
      emitter.emit('change-data', currentQuestList)
      emitter.emit('sort-change', currentQuestList)
      store.commit('set_paper_content', currentQuestList);
    }
    const questExchange = (index, id) => {
      $.modal.create({
        title: '换题',
        zIndex: 2011,
        component: ExchangeComponent,
        props: { id }
      }).then((res: any) => {
        if (res) {
          let data = clone(paperInfo.value.content);
          data[index].question = res;
          data[index].content = res.id;
          emitter.emit('change-data', data)
          emitter.emit('sort-change', data)
          store.commit('set_paper_content', data);
        }
      })
    }
    let changeList: any[] = []
    const editorBlur = (item, index) => {
      let editorList = $.clone(paperInfo.value.content)
      emitter.emit('pid-change', editorList)
      emitter.emit('sort-change', editorList)
      store.commit('set_paper_save', changeList)
      $.http.json('/admin/knowledgeContent/batchSave', editorList)
    }
    const editQuestion = (element, index) => {
      let newList = $.clone(paperInfo.value.content)
      $.drawer.create({ title: '编辑题目', component: updateComponent, width: 840, props: { id: element.question.id } }).then((res) => {
        if (res.result) {
          element.question = res.json
          newList.splice(index, 1, element)
          store.commit('set_paper_init', newList);
        }
      });
    }
    const changeImg = (index, imgItem) => {
      paperInfo.value.content[index].cssType = imgItem.cssType;
      emitter.emit('sort-change', paperInfo.value.content)
      store.commit('set_paper_content', paperInfo.value.content)
    }
    const titleChange = () => {
      let params = {
        title: title.value,
        id: moduleId.value
      }
      $.http.json('/admin/knowledgeManager/saveOrUpdate', params)
    }
    const changeQuestionType = (element, index) => {
      if (element.index !== 1) {
        paperInfo.value.content[index].type = 8;
        emitter.emit('change-data', paperInfo.value.content)
        ElMessage.success('改为变式成功！~')
      } else {
        ElMessage.warning('例一无法改为变式！')
      }
    }
    const changeQuestion = (element, index) => {
      paperInfo.value.content[index].type = 4;
      emitter.emit('change-data', paperInfo.value.content)
      ElMessage.success('改为例题成功！~')
    }
    return {
      paperInfo, deleteQuestType, handle, questExchange, title, addKnowledge, addQuestion, dragEnd,  addChangeQues,
      editorBlur, editQuestion, choiceImg, changeImg, emitter, titleChange, changeQuestionType, changeQuestion, getImg, baseApi, xkwQuesAdd, quesAdd
      ,practiceAdd, xkwPracticeAdd }
  }
}
</script>
<style lang="scss">
.editorI {
  position: relative;
  i {
    font-style: italic !important;
  }
}
</style>
<style lang="scss" scoped>
@import './edit-content.scss';
:deep(.cus__editable__content) {
  border: none;
}
</style>
